<script>
import {detailBlog, addBlog} from "../../api/blog";
import {ElMessage} from "element-plus";
import UploadItem from "../../components/resource/UploadItem.vue";
import {listGroups} from "../../api/group";
import {listTypes} from "../../api/dict";
import {uploadImage, uploadResource} from "../../api/file";
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
export default {
    name: "MarkdownEditor",
    components: {UploadItem,mavonEditor},
    data() {
        return {
            blog: {
                title: '',
                content: '',
                tag: [],
                type: null,
            },
            dialogVisible: false,
            inputVisible: false,
            inputValue: '',
            dialogImageUrl: '',
            imgVisible: false,
            groups: [],
            fileList: [],
            props: {
                lazy: true,
                value: 'id',
                label: 'name',
                emitPath: false,
                lazyLoad(node, resolve) {
                    const {level, value} = node

                    if (level === 0) {
                        listTypes(0,"resType")
                            .then(res => {
                                resolve(res.data)
                            })
                    } else {
                        listTypes(value,"resType")
                            .then(res => {
                                resolve(res.data)
                            })
                    }

                },
            },
        }
    },
    computed: {
        user() {
            return this.$store.state.userInfo;
        },
    },
    methods: {
        handleChange(file, fileList) {
            if (fileList.length > 1)
                fileList.splice(0, 1)
            this.fileList = fileList
        },
        goBack() {
            this.$router.back()
        },
        publishBlog() {
            //判断是否更新img
            if (this.fileList.length === 0 || this.fileList[0].name === 'banner') {
                addBlog(JSON.stringify(this.blog))
                    .then(res => {
                        if (res.code === 200) {
                            ElMessage.success("发布成功")
                        } else ElMessage.error("发布失败")
                    })
            } else
                this.$refs.up.submit();
            this.dialogVisible = false
        },
        saveInLocal() {

        },
        handleClose(tag) {
            this.blog.tag.splice(this.blog.tag.indexOf(tag), 1)
        },

        showInput() {
            this.inputVisible = true
            this.$nextTick((_) => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },

        handleInputConfirm() {
            const inputValue = this.inputValue
            if (inputValue) {
                this.blog.tag.push(inputValue)
            }
            this.inputVisible = false
            this.inputValue = ''
        },

        handleRemove(file, fileList) {
            console.log(file, fileList)
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url
            this.imgVisible = true
        },

        getGroups() {
            listGroups(this.user.userId)
                .then(res => {
                    this.groups = res.data;
                })
        },
        // 绑定@imgAdd event
        imgAdd(pos, file) {
            // 第一步.将图片上传到服务器.
            const formdata = new FormData();
            formdata.append('file', file);
            uploadImage(formdata)
                .then(res => {
                    this.$refs.md.$img2Url(pos, res.data)
                })
        },
        elUploadImg(param) {
            const formData = new FormData()
            formData.append('file', param.file)
            uploadImage(formData)
                .then(res => {
                    if (res.code === 200) {
                        this.blog.banner = res.data
                        this.blog.ownerId = this.user.userId
                        addBlog(JSON.stringify(this.blog))
                            .then(res => {
                                if (res.code === 200) {
                                    ElMessage.success("发布成功")
                                } else ElMessage.error("发布失败")
                            })
                    }
                })

        },
        init() {
            var id = this.$route.query['id']
            if (id) {
                detailBlog(id)
                    .then(res => {
                        if (res.code === 200) {
                            this.blog = res.data;
                            this.blog.tag = JSON.parse(this.blog.tag)
                            this.fileList.push({name: 'banner', url: this.blog.banner})
                        }
                    })
            }
        }
    },

    mounted() {
        this.getGroups()
        this.init()
    },
    unmounted() {
    }
}
</script>

<template>
    <div class="flex column align-center" style="height: 100vh;width: 100%">
        <!--        head-->
        <div class="flex row align-center center head">
            <div @click="goBack" class="flex row align-center center"
                 style="margin-left: 60px;margin-right:30px;cursor: pointer;color: #6b6b6b;width: fit-content">
                <img src="../../assets/logo_color.svg" alt="" width="40" height="40">
                <h3 style="width: fit-content">GoBack</h3>
            </div>
            <el-input maxlength="130" show-word-limit v-model="blog.title" placeholder="文章标题" class="title"></el-input>
            <el-button class="save" style="margin-left: 30px;border-radius: 15px;width: 100px">保存草稿</el-button>
            <el-button class="publish" @click="dialogVisible=true"
                       style="margin-right: 30px;border-radius: 15px;width: 100px">
                发布文章
            </el-button>
            <img v-if="user" :src="user.avatar" style="margin-right: 60px;border-radius: 20px;cursor: pointer"
                 :width="40" :height="40">

        </div>
        <div style="width: 100%;height: calc(100vh - 60px)">
            <mavonEditor ref="md"  @imgAdd="imgAdd" style="height: 100%" fontSize="14pt"
                          v-model="blog.content"
                          codeStyle="xcode"
            />
        </div>
    </div>
    <el-dialog
        v-model="dialogVisible"
        custom-class="dialog"
        title="发布文章"
        width="35%">
        <div class="flex column space-between align-center" style="width: 100%;height: 450px">
            <div class="flex row  flex-start " style="width: 100%">
                <span style="width: 100px">文章封面:</span>
                <el-upload
                    action="#"
                    :file-list="fileList"
                    list-type="picture-card"
                    :auto-upload="false"
                    ref="up"
                    :on-change="handleChange"
                    :on-preview="handlePictureCardPreview"
                    :http-request="elUploadImg"
                    :on-remove="handleRemove">
                    <div class="flex center align-center"
                         style="border: 1px ;border-radius: 15px;width: 100%;height: 100%">
                        <img style="width: 50%;height: 50%;" src="../../assets/img/upload.svg" alt="">
                    </div>
                </el-upload>
                <el-dialog v-model="imgVisible">
                    <img width="100%" :src="dialogImageUrl" alt=""/>
                </el-dialog>
            </div>
            <div class="flex row center flex-start " style="width: 100%">
                <span style="width: 120px">文章摘要:</span>
                <el-input v-model="blog.summary" placeholder="输入文章简要的介绍" type="textarea"/>
            </div>
            <div class="flex row center flex-start " style="width: 100%">
                <span style="width: 120px">文章类别:</span>
                <el-cascader
                    v-model="blog.typeId"
                    style="width: 100%"
                    :props="props"
                    placeholder="选择资料类别"
                />
            </div>
            <div class="flex row center flex-start " style="width: 100%">
                <span style="width: 120px">文章专栏:</span>
                <el-select
                    v-model="blog.groupId"
                    filterable
                    allow-create
                    default-first-option
                    style="width: 100%"
                    placeholder="选择或输入分组名称"
                >
                    <el-option
                        v-for="item in groups"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </div>
            <div class="flex row center flex-start " style="width: 100%;height: 60px">
                <span style="width: 120px">文章标签:</span>
                <div style="width: 100%">
                    <el-tag v-for="tag in blog.tag" :key="tag" closable :disable-transitions="false"
                            @close="handleClose(tag)">{{ tag }}
                    </el-tag>
                    <el-input v-if="inputVisible" ref="saveTagInput" v-model="inputValue" class="input-new-tag"
                              size="mini" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm"></el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">添加标签</el-button>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="publishBlog">发布</el-button>
             </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.save {
    border-color: #FF6700;
    background: white;
    color: #FF6700;
}

.publish {
    background: #FF6700;
    border-color: #FF6700;
    color: white;
}

.save:hover {
    background: #FF670022;
}

.publish:hover {
    background: #ff4400
}

:deep(.op-icon) {
    height: 100% !important;
    width: 40px !important;
    font-size: 18px !important;
    margin: 0 2px !important;
    border-radius: 0 !important;
}

.head {
    height: 60px;
    background: white;
    width: 100%;
    box-shadow: 0 2px 13px 0 rgba(0, 0, 0, 0.1);
}

.title:deep(.el-input__inner) {

    border-radius: 20px !important;
    font-size: 14pt;

}

.button-new-tag {
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
}

</style>

<style>
.dialog {
    border-radius: 15px !important;
}

</style>
